import msg from "../../../utils/msg";
import { activity_detail, activity_list, join_activity, revoke_join_activity, subscribe } from "../../../utils/request/api";
import User from "../../../utils/user";
import { isFutureDate } from "../../../utils/util";
import Notify from '../../../miniprogram_npm/@vant/weapp/notify/notify';
// pages/act/actDetail/actDetail.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    act: {} as any,
    big_pics: [],
    playerList: [] as { id: string, sign_gfid: number, sign_gftx: string, sign_name: string }[],
    playerNum: 0,
    showPhone: false,
    has_joined: false,
    id: '',
  },
  viewAct() {
    let club_id = this.data.act.club.club_id;
    wx.navigateTo({
      url: '/pages/user/myActiv/myActiv' + '?club_id=' + club_id,
    });
  },
  _removeJavaScript(html: string): string {
    // 使用正则表达式匹配并移除<script>标签及其内容
    const regex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
    return html.replace(regex, '');
  },
  //获取报名状态
  getJoinedState() {
    let user = new User;
    let playerList = this.data.playerList;
    playerList.forEach((item) => {
      if (item.sign_gfid == user.GF_ID) {
        this.setData({
          has_joined: true,
        });
      }
    });
  },
  goToMain() {
    wx.switchTab({
      url: "/pages/act/act",
    })
  },
  //关注-取关
  follow: async function () {
    let club = this.data.act.club;
    if (club.is_subscribe) {
      await msg.confirm('是否确认取关', '');
    }
    //todo 储存关注
    let user = new User;
    let res: any = await subscribe({ GF_ID: user.GF_ID, type: 1, control: (club.is_subscribe ? 0 : 1), id: club.club_id });
    if (res.data.error == 0) Notify({ type: (club.is_subscribe ? 'warning' : 'success'), message: (club.is_subscribe ? '取消关注' : '关注成功') });
    else Notify({ type: "danger", message: res.data.msg });

    this.setData({
      ['act.club.is_subscribe']: (club.is_subscribe ? 0 : 1),
    });
  },
  openMap() {
    msg.show('该活动不支持定位', '');
  },
  //收藏-取关
  store: async function () {
    let following = (this.data.act.is_attention == 1);
    if (following) {
      await msg.confirm('是否取消收藏', '');
    }
    //todo 储存关注
    let user = new User;
    let res: any = await subscribe({ GF_ID: user.GF_ID, type: 3, control: (following ? 0 : 1), id: this.data.act.id });
    if (res.data.error == 0) Notify({ type: (following ? 'warning' : 'success'), message: (following ? '取消收藏' : '收藏成功') });
    else Notify({ type: "danger", message: res.data.msg });
    this.setData({
      ['act.is_attention']: (following ? 0 : 1),
      ['act.attention_num']:(following ? this.data.act.attention_num-1 : this.data.act.attention_num+1),
    });
  },
  onSelectPhone(event: any) {
    wx.makePhoneCall({
      phoneNumber: event.detail.name,
      success: function (res) {
        console.log("拨打电话成功！", res)
      },
      fail: function (err) {
        console.log("拨打电话失败！", err)
      }
    })
  },
  onClose() {
    this.setData({
      showPhone: false,
    });
  },
  showPhone() {
    this.setData({
      showPhone: true
    });
  },
  join: async function () {
    let user = new User();
    if (!user.checkLogin(1)) return;

    let res: any;
    if (!this.data.has_joined) {
      //检查是否满员
      if (this.data.act.apply_number <= (this.data.playerList.length + this.data.playerNum)) {
        msg.show('报名人数已满'); return;
      }
      wx.navigateTo({
        url: "/pages/pay/pay" + "?id=" + this.data.act.id + '&type=2',
      });
    }
    else {
      //重复报名
      await msg.confirm('您已申请报名该活动', '若要退出报名，请点击确认');
      await msg.confirm('为防止误触，请再次确认是否退出该活动的报名', '活动名称:' + this.data.act.activity_title);
      //退出报名
      msg.Loading();
      res = await revoke_join_activity({ GF_ID: user.GF_ID, activity_data_id: this.data.act.acitivty_data_id });
      if (res.data.error == 0) {
        this.setData({
          has_joined: false,
        });
        this.onShow();
        Notify({ type: "danger", message: '退出报名成功' });
      }
    }
  },
  //判断是否可以报名
  judgeSignValid() {
    let sign_end = this.data.act.sign_up_date_end;
    console.log('sign_end=',sign_end);
    this.setData({
      signValid: isFutureDate(sign_end),
    });
  },
  onLoad: async function (options: any) {
    let id = options.id;
    this.setData({
      id: id,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    let id = this.data.id;
    let user = new User;
    msg.Loading();
    let res: any = await activity_detail({ activity_id: id, GF_ID: user.GF_ID.toString() });
    if (res.data.error != 0) {
      msg.showErr(); return;
    }
    let act = res.data.datas;
    if (act.sign_up_date) act.sign_up_date = act.sign_up_date.replaceAll('-', '/');
    if (act.activity_time) act.activity_time = act.activity_time.replaceAll('-', '/');
    if (act.activity_time_end) act.activity_time_end = act.activity_time_end.replaceAll('-', '/');
    if (act.sign_up_date_end) act.sign_up_date_end = act.sign_up_date_end.replaceAll('-', '/');
    act.intro_content = this._removeJavaScript(act.intro_content);
    this.setData({
      act: act,
    });
    let playerList: any[] = res.data.sign_datas;
    if (playerList) {
      let playerNum = 0;
      if (playerList.length > 6) {
        playerList.splice(4, playerList.length - 5);
        playerNum = playerList.length;
      }
      this.setData({
        playerList: playerList,
        playerNum,
      });
    }

    this.getJoinedState();
    this.judgeSignValid();
    //轮播图
    if (act.activity_big_pic)
      this.setData({
        big_pics: act.activity_big_pic.split(','),
      });


    msg.hideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})